package org.example.myleet.p1609;

import org.example.myleet.Utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public boolean isEvenOddTree(TreeNode root) {
        int level = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            boolean evenLevel = (level & 1) == 0;
            int last = Integer.MIN_VALUE;
            for (int i = 0; i < len; ++i) {
                TreeNode node = queue.poll();
                if (null != node.left) {
                    queue.offer(node.left);
                }
                if (null != node.right) {
                    queue.offer(node.right);
                }
                if (last != Integer.MIN_VALUE) {
                    if (evenLevel) {
                        if (last >= node.val) {
                            return false;
                        }
                    } else {
                        if (last <= node.val) {
                            return false;
                        }
                    }
                }
                last = node.val;
                boolean odd = isOdd(last);
                if (evenLevel) {
                    if (!odd) {
                        return false;
                    }
                } else {
                    if (odd) {
                        return false;
                    }
                }
            }
            ++level;
        }
        return true;
    }

    private boolean isOdd(int n) {
        return (n & 1) == 1;
    }
}
